package com.jose.photogallery.domain;

import com.googlecode.objectify.NotFoundException;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.googlecode.objectify.util.DAOBase;

public class PhotogalleryDAO extends DAOBase {
	static {
		ObjectifyService.register(Photo.class);
		ObjectifyService.register(Rating.class);
	}
	
	public PhotogalleryDAO(){
		
	}

	/*
	 * Inicialize an DAO object for transaction
	 */
	public PhotogalleryDAO(ObjectifyOpts opts){
		super(opts);
	}
	
	// methods for getting the data
	public Photo getPhoto(String key) {
		try {
			Photo photo = this.ofy().get(Photo.class, key);
			return photo;
		} catch (NotFoundException e) {
			return null;
		}
	}

	public Query<Photo> getTop() {
		Query<Photo> q = this.ofy().query(Photo.class).order("-rating");
		return q;
	}

	public Query<Photo> getLates() {
		Query<Photo> q = this.ofy().query(Photo.class).order("-updateDate");
		return q;
	}

	public Query<Photo> getUserPhotos(String user) {
		Query<Photo> q = this.ofy().query(Photo.class).filter("user =", user);
		return q;
	}

	// Save or Update a Photo
	public String savePhoto(Photo photo) {
		this.ofy().put(photo);
		return photo.getBlobKey();

	}
	
	//Save or Update a Rating
	public String saveRating(Rating rating) {
		this.ofy().put(rating);
		return rating.getKey();
	}
	
	public Rating getRating(String key) {
		try {
			Rating rating = this.ofy().get(Rating.class, key);
			return rating;
		} catch (NotFoundException e) {
			return null;
		}
	}
}
